package com.flyqiu.form.extensions.convert;

import com.flyqiu.common.single.FlyQiuSingletonFactory;
import com.flyqiu.common.single.FlyQiyBaseSingleton;
import com.flyqiu.form.extensions.convert.mapping.*;

import java.util.HashMap;
import java.util.Map;

/**
 * FlyQiuAvueMapperConfig 类用于配置 Avue 表单映射器的全局信息
 * 它采用了单例模式来确保全局只有一个实例
 */
public class FlyQiuAvueMapperConfig extends FlyQiyBaseSingleton {
    // 存储映射器类型和对应类的映射关系
    private static final Map<String, Class<? extends FlyQiuAvueMapper>> configMapper = new HashMap<>();
    // 全局默认映射器类
    private static Class<? extends FlyQiuAvueMapper> GLOBAL_DEF_MAPPER = AvueDateMapper.class;

    /**
     * 获取 FlyQiuAvueMapperConfig 的实例
     *
     * @return FlyQiuAvueMapperConfig 的实例
     */
    public static FlyQiuAvueMapperConfig getInstance() {
        return FlyQiuSingletonFactory.get(FlyQiuAvueMapperConfig.class);
    }

    /**
     * 初始化映射器配置
     * 将各种 Avue 映射器类按照类型存储到映射关系表中
     */
    @Override
    public void init() {
        configMapper.put(AvueDefaultMapper.MAPPER_TYPE, AvueDefaultMapper.class);
        configMapper.put(AvueInputMapper.MAPPER_TYPE, AvueInputMapper.class);
        configMapper.put(AvueCascaderMapper.MAPPER_TYPE, AvueCascaderMapper.class);
        configMapper.put(AvueCheckBoxMapper.MAPPER_TYPE, AvueCheckBoxMapper.class);
        configMapper.put(AvueDateMapper.MAPPER_TYPE_DATE, AvueDateMapper.class);
        configMapper.put(AvueDateMapper.MAPPER_TYPE_TIME, AvueDateMapper.class);
        configMapper.put(AvueDateMapper.MAPPER_TYPE_DATE_TIME, AvueDateMapper.class);
        configMapper.put(AvueNumberMapper.MAPPER_TYPE, AvueNumberMapper.class);
        configMapper.put(AvueRadioMapper.MAPPER_TYPE, AvueRadioMapper.class);
        configMapper.put(AvueSelectMapper.MAPPER_TYPE, AvueSelectMapper.class);
        configMapper.put(AvueMapMapper.MAPPER_TYPE_2, AvueMapMapper.class);
        configMapper.put(AvueDynamicMapper.MAPPER_TYPE, AvueDynamicMapper.class);
    }

    /**
     * 获取配置的映射器映射关系表
     *
     * @return 映射器映射关系表
     */
    public Map<String, Class<? extends FlyQiuAvueMapper>> getConfigMapper() {
        return configMapper;
    }

    /**
     * 设置全局默认映射器类
     *
     * @param mapperClazz 全局默认映射器类
     */
    public static void setGlobalDefMapper(Class<? extends FlyQiuAvueMapper> mapperClazz) {
        if (mapperClazz == null) {
            throw new RuntimeException("mapperClazz Cannot be null");
        }
        GLOBAL_DEF_MAPPER = mapperClazz;
    }

    /**
     * 获取全局默认映射器类
     *
     * @return 全局默认映射器类
     */
    public static Class<? extends FlyQiuAvueMapper> getGlobalDefMapper() {
        return GLOBAL_DEF_MAPPER;
    }

    /**
     * 注册自定义映射器
     * 将自定义映射器类按照类型存储到映射关系表中
     *
     * @param colType 列类型
     * @param clazz   映射器类
     */
    public void register(String colType, Class<? extends FlyQiuAvueMapper> clazz) {
        configMapper.put(colType, clazz);
    }
}
